package com.asap.demo.utils;

import com.asap.demo.model.BeanField;
import com.asap.demo.rete.ReteDemo4;
import com.asap.demo.rete.ReteDemo5;
import net.sf.cglib.beans.BeanGenerator;
import net.sf.cglib.beans.BeanMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.*;

/**
 * @author wangbh
 * @Description: 工具类
 * @date 2021/7/6 17:49
 */
public class Utils {
    public static final String DATE_FORMAT_UTC = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS";
    public static final String DATE_FORMAT_FULL = "yyyy-MM-dd HH:mm:ss";

    public static String transforDate(String timeStamp) {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_FULL);
        try {
            Date dt = sdf.parse(timeStamp);
            return sdf.format(dt);
        } catch (ParseException ex) {
        }
        return transforDateUtc(timeStamp);
    }

    public static String transforDateUtc(String timeStamp) {
        SimpleDateFormat sdfUtc = new SimpleDateFormat(DATE_FORMAT_UTC);
        //timeStamp = timeStamp.replace("Z", " UTC");//注意是空格+UTC
        try {
            Date dt = sdfUtc.parse(timeStamp);
            return new SimpleDateFormat(DATE_FORMAT_FULL).format(dt);
        } catch (ParseException e) {
            return timeStamp;
        }
    }

    public static Date transforDateForDate(String timeStamp) {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_FULL);
        try {
            Date dt = sdf.parse(timeStamp);
            return dt;
        } catch (ParseException ex) {
        }
        return transforDateUtcForDate(timeStamp);
    }

    public static Date transforDateUtcForDate(String timeStamp) {
        SimpleDateFormat sdfUtc = new SimpleDateFormat(DATE_FORMAT_UTC);
        //timeStamp = timeStamp.replace("Z", " UTC");//注意是空格+UTC
        try {
            Date dt = sdfUtc.parse(timeStamp);
            return dt;
        } catch (ParseException e) {
            return  new Date();
        }
    }

    public static String transforDateUtc1(String timeStamp) {
        SimpleDateFormat sdfUtc = new SimpleDateFormat(DATE_FORMAT_UTC);
        //timeStamp = timeStamp.replace("Z", " UTC");//注意是空格+UTC
        try {
            Date dt = sdfUtc.parse(timeStamp);
            return  new SimpleDateFormat(DATE_FORMAT_UTC).format(dt);
        } catch (ParseException e) {
            return timeStamp;
        }
    }
    /**
     * Map转实体类共通方法
     *
     * @param type 实体类class
     * @param map map
     * @return Object
     * @throws Exception
     */
    public static Object convertMap(Class type, Map map) throws Exception {
        BeanInfo beanInfo = Introspector.getBeanInfo(type);
        Object obj = type.newInstance();
        PropertyDescriptor[] propertyDescriptors =  beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor descriptor : propertyDescriptors) {
            String propertyName = descriptor.getName();
            if (map.containsKey(propertyName)) {
                Object value = map.get(propertyName);
                descriptor.getWriteMethod().invoke(obj, value);
            }
        }
        return obj;
    }

    /**
     * 实体类转Map共通方法
     *
     * @param bean 实体类
     * @return Map
     * @throws Exception
     */
    public static Map convertBean(Object bean) throws Exception {
        Class type = bean.getClass();
        Map returnMap = new HashMap();
        BeanInfo beanInfo = Introspector.getBeanInfo(type);
        PropertyDescriptor[] propertyDescriptors =  beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor descriptor : propertyDescriptors) {
            String propertyName = descriptor.getName();
            if (!propertyName.equals("class")) {
                Method readMethod = descriptor.getReadMethod();
                Object result = readMethod.invoke(bean);
                if (result != null) {
                    returnMap.put(propertyName, result);
                } else {
                    returnMap.put(propertyName, "");
                }
            }
        }
        return returnMap;
    }


    public static String getUrlByCode(String code) {
        char[] charArray = code.toCharArray();
        // A-Z 对应数字65-90 a-z 对应数字97-122
        for (int i = 0; i < charArray.length; i++) {
            if (charArray[i] == '_') {
                // 字符在97-122之间的都是小写字母，在原基础上减32转换成大写
                if (charArray[i + 1] >= 97 && charArray[i + 1] <= 122) {
                    int upper = charArray[i + 1] - 32;
                    charArray[i + 1] = (char) upper;
                }
            }
        }
        StringBuffer url = new StringBuffer("");
        for (int i = 0; i < charArray.length; i++) {
            url.append(charArray[i]);
        }
        return url.toString().replace("_", "");
    }

    public static Object generateObject(Map properties) {
        BeanGenerator generator = new BeanGenerator();
        Set keySet = properties.keySet();
        for(Iterator i = keySet.iterator(); i.hasNext();) {
            String key = (String)i.next();
            generator.addProperty(key, (Class)properties.get(key));
        }
        return generator.create();
    }

    private static Object getValue(Object obj, String property) {
        BeanMap beanMap = BeanMap.create(obj);
        return beanMap.get(property);
    }

    public static void setValue(Object obj, String property, Object value) {
        BeanMap beanMap = BeanMap.create(obj);
        beanMap.put(property, value);
    }
    public static boolean checkAllNumber(String fieldValue) {
        boolean result = true;
        if (fieldValue == null || fieldValue.isEmpty()) {
            return true;
        }

        for (int idx = 0, len = fieldValue.length(); idx < len; idx++) {
            if ((fieldValue.charAt(idx) < '0' || fieldValue.charAt(idx) > '9') && fieldValue.charAt(idx) != ' '
                    && fieldValue.charAt(idx) != '-') {
                result = false;
                break;
            }
            if ((fieldValue.charAt(idx) == '.')) {
                result = false;
                break;
            }
        }
        return result;
    }

    /**
     * 通过反射写一个类，类中有个方法。
     * 该方法可以设置某个类中的某个属性（构造方法，成员变量，成员方法）为特定的值
     * @param obj
     * @param fieldName
     * @param value
     */
    public static void setFieldValueByName(Class c ,Object obj, String fieldName, Object value){
        try {
            // 获取该类的成员变量
            Field f = c.getDeclaredField(fieldName);
            // 取消语言访问检查
            f.setAccessible(true);
            // 给变量赋值
            f.set(obj, value);
        } catch (Exception e) {
            System.out.println(e);
        }

    }
    /**
     * @Function:     join 
     * @Description:  字符串拼接
     *
     * @param separator
     * @param parts
     * @return
     */
    public static String join(String separator, String... parts) {

        if (separator == null || separator.isEmpty()) {
            return join(parts);
        }

        if (parts != null && parts.length > 0) {
            StringBuilder buf = new StringBuilder();
            for (String part : parts) {
                buf.append(part).append(separator);
            }
            return buf.substring(0, buf.length() - separator.length());
        }
        return null;
    }

    /**
     * 字符串拼接
     *
     * @param array 字符数组
     * @return
     */
    public static String join(String[] array) {
        if (array.length == 0) {
            return "";
        } else {
            StringBuilder sb = new StringBuilder();
            String[] var5 = array;
            int var4 = array.length;

            for (int var3 = 0; var3 < var4; ++var3) {
                String s = var5[var3];
                sb.append(s);
            }

            return sb.toString();
        }
    }


    public static void testForUrl(List<String> strUrl) throws IOException {

        HttpURLConnection connection =null;
        BufferedReader reader=null;
        long size = strUrl.size();
        Random r = new Random(1);
        long threadId=  Thread.currentThread().getId();
        try {
            while(true) {

                int cnt = (int) ((r.nextInt(100)+threadId)%size);

                String urlTmp = strUrl.get(cnt);
                URL url = new URL(urlTmp);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                // 发送数据到服务器并使用Reader读取返回的数据
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                reader.readLine();
                reader.close();
                connection.disconnect();
                System.out.println("get " + urlTmp + " ThreadName:" + Thread.currentThread().getName());

                Thread.sleep(20000);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            reader.close();
            connection.disconnect();
        }

    }

    public static String read(String fileName)
    {
        String data = null;
        FileInputStream fileInputStream =null;
        try{
            fileInputStream = new FileInputStream(new File(fileName));

            int readByte = 0;
            byte[] bytedata = new byte[204800];
            while(-1 != (readByte = fileInputStream.read(bytedata))){
            }

            data = new String(bytedata);
        }catch(IOException e){
            //logger.error(" ",e);
        }finally {
            if(fileInputStream!=null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                  //  logger.error("fileInputStream.close() ",e);
                }
            }
        }

        return data;
    }

}
